/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from 'react';
import { Dropdown, Menu, Input ,Icon} from 'antd';
import classNames from 'classnames';
import styles from './index.less';
import KbIcon from '../KbIcon';


class KbDropdown extends Component {
  static defaultProps = {
    labelInValue: false,
    onChange: () => {},
    onVisibleChange: () => {},
    bar: '选择',
    title: '',
    overlay: () => {},
    placeholder: '点击选择',
    className: '',
    readOnly: true,
    value: null,
    overlayStyle: {
      maxHeight: 600,
      overflowY: 'auto',
    },
  };

  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
  }

  onVisibleChange = (visible, then = () => {}) => {
    this.setState(
      {
        visible,
      },
      () => {
        then();
        this.props.onVisibleChange(visible);
      }
    );
  };

  openDropDown = () => {
    const { visible } = this.state;
    this.onVisibleChange(!visible);
  };

  onInputChange = e => {
    const { labelInValue, onChange } = this.props;
    const { value } = e.target;
    onChange(labelInValue ? { label: value } : value);
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      this.onVisibleChange(!value);
    }, 100);
  };

  overlay = () => {
    const { overlay, onChange, overlayStyle, title } = this.props;
    return (
      <Menu style={{ ...overlayStyle }}>
        {title && <div className={styles.title}>{title}</div>}
        {overlay(value => {
          this.onVisibleChange(false, () => {
            onChange(value);
          });
        })}
      </Menu>
    );
  };

  render() {
    const { visible } = this.state;
    const { labelInValue, value, bar, placeholder, className, readOnly, style ,text,icon} = this.props;
    return (
      <div
        className={classNames(className, text?'':styles.input, {
          [styles.input_active]: visible&&!text,
        })}
        style={style}
      >
        <Dropdown
          trigger={['click']}
          overlay={this.overlay}
          visible={visible}
          onVisibleChange={this.onVisibleChange}
        >
          {
            text? <a className={styles.text}><KbIcon type={icon || 'down'} /> {bar}</a>:<Input
                value={labelInValue ? value && value.label : value}
                readOnly={readOnly}
                onChange={this.onInputChange}
                placeholder={placeholder}
                addonAfter={<a onClick={this.openDropDown}>{bar}</a>}
            />
          }

        </Dropdown>
      </div>
    );
  }
}

export default KbDropdown;
